<script lang="ts">
export const userModifyPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./index.vue')),
  {
    title: computed(() => $t('xkMs1f4Vsh_0y6sWnFvp1')),
    wrapClassName: 'ant-cover__Modal-drawer __screen-drawer',
    centered: true,
    footer: null,
  },
);
</script>

<script lang="ts" setup>
const appStore = useAppStore();
const userStore = useUserStore();
const { userInfo } = userStore;
const levelAvatarQry = useQuery({
  queryKey: [apis.apiLevelAvatar.id],
  queryFn: () => apis.apiLevelAvatar(undefined),
});
const levelAvatarInfo = computed(() => levelAvatarQry.data.value);
const avatarId = ref(userInfo?.avatar);
const nickname = ref(userInfo?.nickname);

const flag = ref(false);
function onUpdateName() {
  if (!nickname.value) {
    antdMessage.warning($t('0bljHscj64uybCe4IdcfY'));
    return;
  }
  if (nickname?.value.length < 4 || nickname?.value.length > 30) {
    antdMessage.warning($t('zkjCYndkZoSsjrsOfcplL'));
    return;
  }

  onSubmit(userInfo?.avatar ?? 0, nickname.value);
}
function updateAvatar(id: number) {
  avatarId.value = id;
  onSubmit(id, userInfo?.nickname ?? '');
}

function onSubmit(id: number, name: string) {
  const requestBody = {
    avatar: id,
    nickname: name,
  };

  apis.apiUserUpdateNickname({ requestBody }).then(() => {
    queryClient.invalidateQueries({
      queryKey: [apis.apiUserInfo.id],
      exact: false,
    });
  }).then(() => {
    antdMessage.success($t('zsaLk1KtXyRrJmdsq5Jo2'));
    globalPopups.userModify.close?.();
  });
  setTimeout(() => {
    flag.value = false;
  }, 2000);
}

const select = computed(() => avatarId.value ? Number(avatarId.value) : userInfo?.avatar);
const userLevel = computed(() => Number(userInfo?.vip_level?.level));
</script>

<template>
  <div class="h-full flex flex-col">
    <div class="mb-5 w-full text-3.5">
      <form class="grid gap-3" @submit.prevent="onUpdateName">
        <div class="mb-2.5 text-sys-text-body">
          {{ $t('bDiKQFh9RqRfMzfCfqqO') }}
        </div>
        <AInputSearch
          v-model:value="nickname"
          placeholder="input search text"
          :enterButton="$t('dqcvMmkkLelXhEb_6QHcN')"
          size="large"
          allowClear
          :loading="flag"
          @search="onUpdateName"
        />
      </form>
    </div>

    <h2 class="text-4.5 text-sys-text-head">
      {{ $t('ep9RftZi8a6qFKyv1sfqv') }}
    </h2>
    <TSuspenseView
      v-bind="buildSvPropsOfQuery(levelAvatarQry)"
      class="flex-1 overflow-scroll overscroll-none"
    >
      <div v-for="(item, index) in levelAvatarInfo" :key="index">
        <div class="mb-2.5 mt-4 text-3.5 text-sys-text-body leading-normal">
          {{ item.name }}
        </div>
        <div class="grid grid-cols-[repeat(auto-fill,minmax(76px,1fr))] gap-2.5">
          <button
            v-for="(i) in item.avatar" :key="i.avatar_id"
            class="relative h-20 w-20 cursor-pointer rounded-[50%] bg-sys-layer-b p-0"
            :class="select === i.avatar_id ? 'border-(2 solid yellow)' : 'border-(2px solid slate-900)'"
            :disabled="userLevel < i.level"
            @click="updateAvatar(i.avatar_id)"
          >
            <span v-if="select === i.avatar_id" class="absolute bottom-0 right-1 h-4 w-4 flex items-center justify-center rounded-[50%] bg-yellow500">
              <i class="i-local:check-line?mask text-sys-text-head" />
            </span>
            <img
              :src="appStore.joinCdnPath(`${i.path}`)" class="h-19 w-19 rounded-[50%] object-fill"
              :class="userLevel >= i.level ? '' : 'opacity-[40%]'"
            >
            <i v-if="userLevel < i.level" class="i-local:lock-icon absolute left-[50%] top-[50%] transform-translate-[-50%]" />
          </button>
        </div>
      </div>
      <template #pending>
        <TSkeleton class="grid gap-3">
          <TSkeleton type="text" :length="6" class="mb-2.5 mt-4" />
          <div class="grid grid-cols-[repeat(auto-fill,minmax(76px,1fr))] gap-2.5">
            <TSkeleton type="circle" :size="80" />
            <TSkeleton type="circle" :size="80" />
          </div>
          <TSkeleton type="text" :length="6" class="mb-2.5 mt-4" />
          <div class="grid grid-cols-[repeat(auto-fill,minmax(76px,1fr))] gap-2.5">
            <TSkeleton type="circle" :size="80" />
            <TSkeleton type="circle" :size="80" />
            <TSkeleton type="circle" :size="80" />
            <TSkeleton type="circle" :size="80" />
            <TSkeleton type="circle" :size="80" />
          </div>
        </TSkeleton>
      </template>
    </TSuspenseView>
  </div>
</template>
